package session.stateless.CRM;

import entity.CRM.Customer;
import entity.CRM.SaleQuotation;
import entity.CRM.LineItem;
import entity.CRM.ProductPrice;
import entity.CRM.SaleInquiry;
import entity.CRM.SaleLead;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class SaleQuotationBean implements SaleQuotationBeanLocal {
    @PersistenceContext()
    EntityManager em;
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    @EJB
    private SaleInquiryBeanLocal saleInquiryBeanLocal;
    @EJB
    private DiscountBeanLocal discountBeanLocal;
    
    NumberFormat formatter = new DecimalFormat("#0.00");
 
     public List<ProductPrice> getProductPrice() {
        Query q = em.createQuery("SELECT c FROM ProductPrice c");
        return q.getResultList();
    }
    
    public Long convertToSaleQuotation(Long saleInquiryId, List<LineItem> lineItems, Integer leadTime, Integer validityPeriod){
        SaleQuotation saleQuotation = new SaleQuotation();
        SaleInquiry saleInquiry = em.find(SaleInquiry.class,saleInquiryId);        
        SaleLead saleLead = saleInquiry.getSaleLead();
        
        saleQuotation.setSaleLead(saleLead);
        System.out.println("test b4 passing customDiscount"+saleInquiry.getCustomDiscount());
        saleQuotation.setCustomDiscount(saleInquiry.getCustomDiscount());
        System.out.println("test after passing customDiscount"+saleQuotation.getCustomDiscount());
        
        
        List<LineItem> temp_lineItems = new ArrayList<LineItem>();
        for (LineItem lineItem:lineItems)
        {
            if ((lineItem.getLineItemQuantity()!=null)&&(lineItem.getLineItemQuantity()>0))
            {
                LineItem item = saleInquiryBeanLocal.createLineItem_VolumeCustomDiscountIncluded(lineItem.getProductPrice(), lineItem.getLineItemQuantity(), saleInquiry.getCustomDiscount());
                temp_lineItems.add(item);
            }   
        }        

        saleQuotation.setLineItems(temp_lineItems); 
        Date date = new Date();
        saleQuotation.setSaleInquiryDate(dateFormat.format(date));
        saleQuotation.setSaleLead(saleLead);
        saleQuotation.setLeadTime(leadTime);
        saleQuotation.setValidityPeriod(validityPeriod);

        Calendar currentDate = Calendar.getInstance(); 
        currentDate.setTime(currentDate.getTime());
        saleQuotation.setSaleInquiryDate(currentDate.getTime().toString());

        Calendar expiryDate = Calendar.getInstance();
        expiryDate.setTime(currentDate.getTime());
        System.out.println("SQ bean createnewSQ method" +expiryDate.getTime());
        System.out.println(Calendar.DATE+"    "+saleQuotation.getValidityPeriod());
        expiryDate.add(Calendar.DATE, (int) saleQuotation.getValidityPeriod());
        saleQuotation.setExpiryDate(expiryDate.getTime().toString());
        
        em.persist(saleQuotation);
        
        saleLead.getSaleQuotations().add(saleQuotation);
        em.flush();
        
        return saleQuotation.getId();
    }

    public Long createNewSaleQuotation(String saleLeadName, List<LineItem> Items, Integer leadTime, Integer validityPeriod, Double customDiscount) {
        Query query=em.createQuery("SELECT s from SaleLead s WHERE s.saleLeadName =:saleLeadName");
        query.setParameter("saleLeadName", saleLeadName);
        
        SaleLead saleLead = (SaleLead)query.getSingleResult();
        
        if(saleLead==null)
            return new Long(0);        
        else
        {
            SaleQuotation saleQuotation = new SaleQuotation();
            saleQuotation.setLineItems(Items);
            
            Date date = new Date();
            saleQuotation.setSaleInquiryDate(dateFormat.format(date));
            saleQuotation.setSaleLead(saleLead);
            saleQuotation.setLeadTime(leadTime);
            saleQuotation.setValidityPeriod(validityPeriod);
            
            Calendar currentDate = Calendar.getInstance(); 
            currentDate.setTime(currentDate.getTime());
            saleQuotation.setSaleInquiryDate(currentDate.getTime().toString());
            
            Calendar expiryDate = Calendar.getInstance();
            expiryDate.setTime(currentDate.getTime());
            System.out.println("SQ bean createnewSQ method" +expiryDate.getTime());
            System.out.println(Calendar.DATE+"    "+saleQuotation.getValidityPeriod());
            expiryDate.add(Calendar.DATE, (int) saleQuotation.getValidityPeriod());
            saleQuotation.setExpiryDate(expiryDate.getTime().toString());
            
            saleQuotation.setCustomDiscount(customDiscount);
            em.persist(saleQuotation);
            
            saleLead.getSaleQuotations().add(saleQuotation);
            em.flush();
            
            return saleQuotation.getId();
        }
    }

    public void updateSaleQuotation(Long saleQuotationId,List<LineItem> lineItems) {
        SaleQuotation saleQuotation = em.find(SaleQuotation.class, saleQuotationId);

        List<LineItem> temp_LineItem = saleQuotation.getLineItems();
        saleQuotation.setLineItems(null);
        for (LineItem lineItem : temp_LineItem) {
            saleInquiryBeanLocal.deleteLineItem(lineItem.getLineItemId());
        }

        List<LineItem> temp = new ArrayList<LineItem>();

        for (LineItem item : lineItems) {
            if ((item.getLineItemQuantity() != null) & (item.getLineItemQuantity() > 0)) {
                LineItem lt = saleInquiryBeanLocal.createLineItem_VolumeCustomDiscountIncluded(item.getProductPrice(), item.getLineItemQuantity(), saleQuotation.getCustomDiscount());
                temp.add(lt);
            }
        }

        saleQuotation.setLineItems(temp);
        em.flush();
    }

    public void deleteSaleQuotation(Long saleQuotationId) {
        SaleQuotation saleQuotation = em.find(SaleQuotation.class, saleQuotationId);
        if (saleQuotation == null) {
            System.out.println("Delete sale quotation error!");
        } else {
            List<LineItem> temp = saleQuotation.getLineItems();
            saleQuotation.setLineItems(null);

            for (LineItem lineItem : temp) {
                saleInquiryBeanLocal.deleteLineItem(lineItem.getLineItemId());
            }

            saleQuotation.getSaleLead().getSaleQuotations().remove(saleQuotation);
            em.remove(saleQuotation);
            em.flush();
        }
    }

    public List<SaleQuotation> getSaleQuotation() {
        Query q = em.createQuery("SELECT c FROM SaleQuotation c");
        return q.getResultList();
    }

    public List<SaleQuotation> getSaleQuotationBySaleLead(String registrationNumber) {
        SaleLead saleLead = em.find(SaleLead.class, registrationNumber);
        return (List<SaleQuotation>) saleLead.getSaleQuotations();
    }

    public List<SaleQuotation> getSaleQuotationByCustomer(String registrationNumber) {
        Customer customer = em.find(Customer.class, registrationNumber);
        return (List<SaleQuotation>) customer.getSaleQuotations();
    }

    public double calculateFinalPrice(Long saleInquiryId, ProductPrice product, Long quantity) {
        SaleInquiry saleInquiry = em.find(SaleInquiry.class, saleInquiryId);
        Double customDiscount =saleInquiry.getCustomDiscount();
        Double discountRate=discountBeanLocal.calculateDiscountRate(product.getProductType(), quantity);
        Double finalPrice =product.getProductPrice()*quantity* (1-(discountRate+customDiscount)/100);    
        return finalPrice;
        
    }
}
